import os
import json
from datetime import datetime
from Assignment_and_Grading.course_task_classes import Assignment, Quiz

# 添加配置导入和路径处理
import sys
import os
# 确保能够导入其他模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from User_Management.config import PROJECT_ROOT, DATA_MAIN_FILE

# 获取统一的数据文件路径
def get_data_file_path():
    """获取统一的数据文件路径"""
    return os.path.join(PROJECT_ROOT, DATA_MAIN_FILE)

class DataPersistence:
    """Handles saving and loading of assignment/grade data to storage"""
    
    @staticmethod
    def save_assignments(assignments, file_path=None):
        """Save assignment/quiz data to JSON file"""
        try:
            # 如果没有指定文件路径,使用统一的数据文件
            if file_path is None:
                file_path = get_data_file_path()
            
                # 读取现有数据
                all_data = {}
                if os.path.exists(file_path):
                    with open(file_path, 'r', encoding='utf-8') as f:
                        all_data = json.load(f)
            
                # 保存到主数据文件的assignments字段
                serialized_data = []
                for task in assignments:
                    # 统一的任务数据结构
                    task_data = {
                        "type": task.__class__.__name__,
                        "id": getattr(task, "assignment_id", getattr(task, "quiz_id", None)),
                        "title": getattr(task, "assignment_title", getattr(task, "quiz_title", None)),
                        "content": getattr(task, "assignment_content", None),
                        "due_date": task.due_date.isoformat(),
                        "course_id": task.course.course_id if task.course else None,
                        "submissions": {}
                    }
                
                    # 统一的提交数据结构
                    if hasattr(task, "submissions"):
                        for sid, sub in task.submissions.items():
                            task_data["submissions"][sid] = {
                                "content": sub.get("content", sub.get("answers", None)),
                                "submit_time": sub["submit_time"].isoformat(),
                                "is_late": sub["is_late"],
                                "score": sub.get("score", None),
                                "status": sub.get("status", "已提交")  # 确保默认使用中文状态
                            }
                
                    # Quiz特定属性
                    if isinstance(task, Quiz):
                        task_data.update({
                            "questions": task.questions,
                            "time_limit": task.time_limit
                        })
                
                    serialized_data.append(task_data)
            
                all_data['assignments'] = serialized_data
            
                with open(file_path, 'w', encoding='utf-8') as f:
                    json.dump(all_data, f, ensure_ascii=False, indent=2)
                print(f"作业数据已保存至统一数据文件: {file_path}")
            else:
                # 兼容旧版,直接保存到指定文件
                serialized_data = []
                for task in assignments:
                    # 原有逻辑保持不变
                    if isinstance(task, Assignment):
                        task_data = {
                            "type": "Assignment",
                            "assignment_id": task.assignment_id,
                            "assignment_title": task.assignment_title,
                            "assignment_content": task.assignment_content,
                            "due_date": task.due_date.isoformat(),
                            "course_id": task.course.course_id if task.course else None,
                            "submissions": {
                                sid: {
                                    "content": sub["content"],
                                    "submit_time": sub["submit_time"].isoformat(),
                                    "is_late": sub["is_late"]
                                } for sid, sub in task.submissions.items()
                            }
                        }
                    elif isinstance(task, Quiz):
                        task_data = {
                            "type": "Quiz",
                            "quiz_id": task.quiz_id,
                            "quiz_title": task.quiz_title,
                            "questions": task.questions,
                            "due_date": task.due_date.isoformat(),
                            "course_id": task.course.course_id if task.course else None,
                            "time_limit": task.time_limit,
                            "submissions": {
                                sid: {
                                    "answers": sub["answers"],
                                    "submit_time": sub["submit_time"].isoformat(),
                                    "is_late": sub["is_late"]
                                } for sid, sub in task.submissions.items()
                            }
                        }
                    serialized_data.append(task_data)
                
                with open(file_path, 'w', encoding='utf-8') as f:
                    json.dump(serialized_data, f, indent=2)
                print(f"作业数据已保存至指定文件: {file_path}")
            return True
        except Exception as e:
            print(f"保存作业数据失败: {str(e)}")
            return False

# 修改独立的 load_assignments_from_file 函数
@staticmethod
def load_assignments_from_file(file_path=None):
    """从统一的数据文件或指定文件加载作业数据"""
    try:
        # 如果没有指定文件路径,使用统一的数据文件
        if file_path is None:
            file_path = get_data_file_path()
            
            if not os.path.exists(file_path):
                print(f"2025-10-29 00:45:39,392 - WARNING - 作业/测验数据文件不存在:{file_path},返回空列表与空评分系统")
                return ([], {})
            
            with open(file_path, 'r', encoding='utf-8') as f:
                all_data = json.load(f)
                
            assignments = []
            # 检查是否有作业数据
            if 'assignments' in all_data:
                for task_data in all_data['assignments']:
                    # Recreate Assignment object
                    task_type = task_data.get("type", "")
                    if task_type == "Assignment":
                        # Create a basic Course object reference
                        course = type('Course', (object,), {"course_id": task_data.get("course_id")})
                        
                        # Recreate Assignment
                        assignment = Assignment(
                            assignment_id=task_data.get("assignment_id", task_data.get("id")),
                            assignment_title=task_data.get("assignment_title", task_data.get("title")),
                            assignment_content=task_data.get("assignment_content", task_data.get("content")),
                            due_date=datetime.fromisoformat(task_data["due_date"]),
                            course=course
                        )
                        
                        # Restore submissions
                        for sid, submission in task_data.get("submissions", {}).items():
                            assignment.submissions[sid] = {
                                "content": submission["content"],
                                "submit_time": datetime.fromisoformat(submission["submit_time"]),
                                "is_late": submission["is_late"]
                            }
                        
                        assignments.append(assignment)
                    
                    # Recreate Quiz object
                    elif task_type == "Quiz":
                        # Create a basic Course object reference
                        course = type('Course', (object,), {"course_id": task_data.get("course_id")})
                        
                        # Recreate Quiz
                        quiz = Quiz(
                            quiz_id=task_data.get("quiz_id", task_data.get("id")),
                            quiz_title=task_data.get("quiz_title", task_data.get("title")),
                            questions=task_data["questions"],
                            due_date=datetime.fromisoformat(task_data["due_date"]),
                            course=course,
                            time_limit=task_data["time_limit"]
                        )
                        
                        # Restore submissions
                        for sid, submission in task_data.get("submissions", {}).items():
                            quiz.submissions[sid] = {
                                "answers": submission["answers"],
                                "submit_time": datetime.fromisoformat(submission["submit_time"]),
                                "is_late": submission["is_late"]
                            }
                        
                        assignments.append(quiz)
            
            print(f"✅ 加载了 {len(assignments)} 个作业")
            return (assignments, {})
    except Exception as e:
        print(f"加载作业数据失败: {str(e)}")
        return ([], {})